package cn.yywd_123.biliarchiver.utils;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import java.util.List;

public class BiliVideo {
	String bvid;
	String title;
	String description;
	String coverURL;
	String ownerName;
	int ownerMid;
	List<Page> pages = new ArrayList<>();

	public BiliVideo(String bvid) {
		this.bvid = bvid;
	}

	public void load() {
		JsonObject videoInfo = JsonParser.parseString(HttpsResponse.GET("https://api.bilibili.com/x/web-interface/view?bvid=" + bvid)).getAsJsonObject().getAsJsonObject("data");

		this.title = videoInfo.get("title").getAsString();
		this.description = videoInfo.get("desc").getAsString();
		this.coverURL = videoInfo.get("pic").getAsString();
		this.ownerName = videoInfo.getAsJsonObject("owner").get("name").getAsString();
		this.ownerMid = videoInfo.getAsJsonObject("owner").get("mid").getAsInt();

		for (JsonElement element : videoInfo.getAsJsonArray("pages")) {
			JsonObject page = element.getAsJsonObject();
			pages.add(new Page(page.get("part").getAsString(), page.get("cid").getAsInt(), page.get("page").getAsInt(), page.get("duration").getAsInt()));
		}
	}

	public String getBvid() {
		return bvid;
	}

	public List<Page> getPages() {
		return pages;
	}

	@Override
	public String toString() {
		return "BiliVideo{" +
				"bvid='" + bvid + '\'' +
				", title='" + title + '\'' +
				", description='" + description + '\'' +
				", coverURL='" + coverURL + '\'' +
				", ownerName='" + ownerName + '\'' +
				", ownerMid=" + ownerMid +
				'}';
	}

	public static class Page {
		String title;
		int cid;
		int pageIndex;
		int duration;

		public Page(String title, int cid, int pageIndex, int duration) {
			this.title = title;
			this.cid = cid;
			this.pageIndex = pageIndex;
			this.duration = duration;
		}

		public String getTitle() {
			return title;
		}

		public int getCid() {
			return cid;
		}

		public int getPageIndex() {
			return pageIndex;
		}

		public int getDuration() {
			return duration;
		}

		@Override
		public String toString() {
			return "Page{" +
					"title='" + title + '\'' +
					", cid=" + cid +
					", pageIndex=" + pageIndex +
					", duration=" + duration +
					'}';
		}
	}
}
